//
//  SelectedDishListViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-11.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "SelectedDishListViewController.h"
#import "SelectedDishCell.h"
#import "NSString+Additions.h"
#import "RelationSeatViewController.h"
#import "ComfirmOrderNoSeatViewController.h"
#import "ShopHomeViewController.h"
#import "OrderDetailViewController.h"

#define TABLE_CELL_HEIGHT 54

@interface SelectedDishListViewController ()
{
    int totalCount;
    float totalMoney;
}
@end

@implementation SelectedDishListViewController

- (id)init
{
    self = [super initWithNibClass:[SelectedDishListViewController class]];
    if (self) {
        _dataSource = [[SelectedDishListDataSource alloc] initWithVC:self];
        _selectedDishList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"已点菜单"];
    
    self.selectedDishTable.delegate = self.dataSource;
    self.selectedDishTable.dataSource = self.dataSource;
    
    [self.selectedDishTable reloadData];
    [self.selectedDishTable autoHeight];
    
    [UIView drawBorders:@[_selectedDishTable, _totalView]];
    [UIView autoLayoutVertical:@[_selectedDishTable, _totalView, _btnSubmit]];
    
    _theScrollview.height = ScreenHeight == iPhone4_Height ? iPhone4_ViewHeight : iPhone5_ViewHeight;
    [_theScrollview autoHeight];
    
    [self totalAction];
}

- (IBAction)leftButtonClick:(id)sender
{
    if (_orderSuccess) {
        [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
        [self pushOrPopViewController:[ShopHomeViewController class]];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)selectDishCountFinished
{
    [self totalAction];
}

- (void)totalAction
{
    totalCount = 0;
    totalMoney = 0;
    
    for (NSDictionary *dic in _selectedDishList) {
        int count = [[dic objectForKey:@"fenshu"] intValue];
        float money = [[dic objectForKey:@"price"] floatValue];
        
        totalCount += count;
        totalMoney += money*count;
    }
    
    self.totalCountLabel.text = [NSString stringWithFormat:@"/%d道菜",totalCount];
    self.totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f元",totalMoney];
}

#define 提交订单
- (void)submitOrder
{
    NSString *username = [AppSetting userName];
    NSString *shopId = _shopId;
    NSString *caipin = [self getDishString];
    NSString *seat = self.selectSeats;
    NSString *dinnerCount = S_EMPTY;
    NSString *orderTime = S_EMPTY;
    NSString *zaowan = S_EMPTY;
    NSString *mobile = S_EMPTY;

    NSString *url = [NSString stringWithFormat:API_DISH_ORDER,username,shopId,caipin,dinnerCount,orderTime,zaowan,mobile,seat,S_EMPTY,S_EMPTY];

    [_dataSource submitOrderWithURL:url];
}

#pragma 获取选中的菜品列表
- (NSString*)getDishString
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
     for (NSDictionary *dic in _selectedDishList) {
         if ([[dic objectForKey:@"fenshu"] intValue] > 0) {
             NSString *cid = [dic objectForKey:@"id"];
             NSString *price = [dic objectForKey:@"price"];
             NSString *ccount = [dic objectForKey:@"fenshu"];
             
             NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:cid,@"cid",price,@"price",ccount,@"ccount", nil];
             [array addObject:dictionary];
         }
     }
     
     NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:array,@"caipin", nil];
     return [dictionary JSONString];
}

- (IBAction)doneOrderAction:(id)sender
{
    if (_selectSeats) {
        //直接提交订单
        [self submitOrder];
    }else {
        //跳转到无座位确认订单页面
        ComfirmOrderNoSeatViewController *comfirmVC = [[ComfirmOrderNoSeatViewController alloc] initWithShopId:_shopId];
        comfirmVC.selectedDishList = self.selectedDishList;
        [self.navigationController pushViewController:comfirmVC animated:YES];
    }
}

#pragma 预定成功后，显示对话框
- (void)orderDidSuccess:(NSDictionary *)data
{
    self.orderSuccess = YES;
    self.orderId = [data objectForKey:@"order_id"];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"系统提示" message:@"您的订单预定成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    OrderDetailViewController *orderVC = [[OrderDetailViewController alloc] initWithOrderId:self.orderId andType:NewOrder];
    [self pushViewController:orderVC];
}

@end

//======================================================================================
#pragma ===================数据源、数据请求等封装===========================================
//======================================================================================

#define ORDER_DISH_TAG 1002

@implementation SelectedDishListDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
    }
    
    return self;
}

- (void)submitOrderWithURL:(NSString*)url
{
    [SVProgressHUD show];
    [self get:url tag:ORDER_DISH_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    
    CLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    
    if (request.tag == ORDER_DISH_TAG) {
        int state = [[json objectForKey:@"state"] intValue];
        
        if (state == 1) {
            [_viewController orderDidSuccess:json];
        }
        
        if(state == 2) {
            [AppDelegate showMessage:@"预定的时间不可用"];
        }
    }
}

#pragma ===================加载tableview数据 Begin========================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.viewController.selectedDishList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellId = @"SelectedDishCell";
    SelectedDishCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
    
    NSMutableDictionary *dic = [self.viewController.selectedDishList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    cell.delegate = self.viewController;
    
    return cell;
}

@end
